const { ElNotification } = ElementPlus;

function ImportantSetup() {
    const deviceOptions = ref([
        '车载武器稳定系统',
        '核生化过滤单元',
        '主动防御系统雷达',
        '中央轮胎充放气阀',
        '电子对抗干扰机',
        '装甲悬挂液压阻尼器'
    ]);

// 设置默认选中的设备
    const selectedDevice = ref(deviceOptions.value[0]);
    // 当前时间
    const currentTime = ref('');

    // 连接状态
    const connectionStatus = ref('disconnected'); // 'disconnected', 'connecting', 'connected'

    // 故障码列表
    const apiFaultCodes = ref([
        'MSV-P001', 'MSV-P010', 'MSV-C101',
        'MSV-A201', 'MSV-F301', 'MSV-D401',
        'MSV-N501', 'MSV-E601'
    ]);
    const selectedApiFaultCode = ref('');
    const apiTestResult = ref(null);

    // 图表相关
    const chart = ref(null);
    let chartInstance = null;
    const chartType = ref('temperature'); // 'temperature' or 'vibration'
    const chartData = ref([]); // 存储图表数据

    // 设备状态
    const deviceStatus = ref('正常运行');
    const deviceRuntime = ref(256);
    const currentMetrics = ref({
        temperature: 76,
        vibration: 3.2,
        pressure: 120,
        oilLevel: 85
    });

    // 故障统计
    const faultStats = ref({
        today: 3,
        week: 12,
        pending: 2,
        processing: 4
    });

    // 设备信息
    const deviceInfo = ref([
        {
            name: '设备型号',
            value: 'XC-9000',
            status: '正常',
            statusClass: 'level-low',
            updateTime: '2025-07-14 10:23'
        },
        {
            name: '发动机状态',
            value: 'V8 柴油',
            status: '高温预警',
            statusClass: 'level-medium',
            updateTime: '2025-07-14 10:20'
        },
        {
            name: '液压系统',
            value: 'HP-3000',
            status: '正常',
            statusClass: 'level-low',
            updateTime: '2025-07-14 09:45'
        },
        {
            name: '变速箱',
            value: '8速自动',
            status: '轻微异常',
            statusClass: 'level-medium',
            updateTime: '2025-07-14 10:15'
        },
        {name: '电气系统', value: '24V', status: '正常', statusClass: 'level-low', updateTime: '2025-07-14 09:30'},
        {
            name: '燃油系统',
            value: '共轨直喷',
            status: '正常',
            statusClass: 'level-low',
            updateTime: '2025-07-14 10:05'
        }
    ]);

    // 故障信息
    const faultInfo = ref([
        {
            id: 1,
            code: 'F-2301',
            description: '发动机温度过高',
            level: '高',
            levelClass: 'level-high',
            time: '2025-07-14 09:45',
            status: '待处理'
        },
        {
            id: 2,
            code: 'F-1123',
            description: '液压压力不足',
            level: '中',
            levelClass: 'level-medium',
            time: '2025-07-14 08:30',
            status: '处理中'
        },
        {
            id: 3,
            code: 'F-0456',
            description: '变速箱异响',
            level: '中',
            levelClass: 'level-medium',
            time: '2025-07-13 15:20',
            status: '已处理'
        },
        {
            id: 4,
            code: 'F-3087',
            description: '传感器信号异常',
            level: '低',
            levelClass: 'level-low',
            time: '2025-07-13 11:10',
            status: '待处理'
        },
        {
            id: 5,
            code: 'F-5567',
            description: '油路堵塞',
            level: '高',
            levelClass: 'level-high',
            time: '2025-07-12 16:40',
            status: '已处理'
        }
    ]);

    // 消息通知
    const unreadCount = ref(3);
    const messageDialogVisible = ref(false);
    const messages = ref([
        {
            id: 1,
            title: '发动机高温预警',
            content: '设备001发动机温度超过85℃，请立即检查冷却系统',
            time: '10:20:45',
            read: false,
            type: 'critical',
            faultInfo: 'MSV-P001'
        },
        {
            id: 2,
            title: '液压系统压力异常',
            content: '设备002液压系统压力低于正常值20%，建议检查液压油路',
            time: '09:45:23',
            read: false,
            type: 'warning',
            faultInfo: 'MSV-P010'
        },
        {
            id: 3,
            title: '三防装置流量不足',
            content: '设备003 NBC过滤系统流量不足，需要更换滤毒罐',
            time: '09:15:38',
            read: false,
            type: 'critical',
            faultInfo: 'MSV-C101'
        }
    ]);

    // 记录上次高温报警时间
    const lastHighTempAlertTime = ref(0);

    // 计算设备状态类
    const deviceStatusClass = computed(() => {
        if (deviceStatus.value === '正常运行') return 'level-low';
        if (deviceStatus.value === '轻微异常') return 'level-medium';
        return 'level-high';
    });

    // 连接状态类
    const connectionStatusClass = computed(() => {
        if (connectionStatus.value === 'connected') return 'status-connected';
        if (connectionStatus.value === 'connecting') return 'status-reconnecting';
        return 'status-disconnected';
    });

    // 连接状态文本
    const connectionStatusText = computed(() => {
        if (connectionStatus.value === 'connected') return '已连接';
        if (connectionStatus.value === 'connecting') return '连接中...';
        return '未连接';
    });

    // 更新当前时间
    const updateTime = () => {
        const now = new Date();
        currentTime.value = now.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        });
    };

    // 切换图表数据
    const toggleChartData = () => {
        chartType.value = chartType.value === 'temperature' ? 'vibration' : 'temperature';
        initChart();
    };

    // 重置图表缩放
    const resetZoom = () => {
        if (chartInstance) {
            chartInstance.dispatchAction({
                type: 'dataZoom',
                start: 0,
                end: 100
            });
        }
    };

    // 初始化图表
    const initChart = () => {
        if (chartInstance) {
            chartInstance.dispose();
        }

        chartInstance = echarts.init(chart.value);

        const option = {
            backgroundColor: 'transparent',
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    return `${params[0].name}<br/>${chartType.value === 'temperature' ? '温度' : '振动幅度'}: ${params[0].value[1]}`;
                },
                backgroundColor: 'rgba(15, 28, 60, 0.9)',
                borderColor: '#3b82f6',
                textStyle: {
                    color: '#e0e6f0'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                top: '10%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: chartData.value.map(item => item.name),
                axisLine: {
                    lineStyle: {
                        color: '#4b5563'
                    }
                },
                axisLabel: {
                    color: '#9ca3af'
                }
            },
            yAxis: {
                type: 'value',
                name: chartType.value === 'temperature' ? '温度 (°C)' : '振动幅度 (g)',
                nameTextStyle: {
                    color: '#9ca3af'
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(75, 85, 99, 0.5)'
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: '#4b5563'
                    }
                },
                axisLabel: {
                    color: '#9ca3af'
                }
            },
            series: [
                {
                    name: chartType.value === 'temperature' ? '温度' : '振动幅度',
                    type: 'line',
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 6,
                    data: chartData.value.map(item => item.value),
                    lineStyle: {
                        width: 3,
                        color: chartType.value === 'temperature' ? '#f87171' : '#60a5fa'
                    },
                    itemStyle: {
                        color: chartType.value === 'temperature' ? '#f87171' : '#60a5fa'
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {
                                offset: 0,
                                color: chartType.value === 'temperature' ? 'rgba(248, 113, 113, 0.5)' : 'rgba(96, 165, 250, 0.5)'
                            },
                            {
                                offset: 1,
                                color: chartType.value === 'temperature' ? 'rgba(248, 113, 113, 0.1)' : 'rgba(96, 165, 250, 0.1)'
                            }
                        ])
                    },
                    markLine: {
                        silent: true,
                        lineStyle: {
                            color: chartType.value === 'temperature' ? '#f87171' : '#60a5fa',
                            type: 'dashed'
                        },
                        data: [
                            {
                                yAxis: chartType.value === 'temperature' ? 85 : 5.0,
                                label: {
                                    formatter: '警戒线',
                                    position: 'end'
                                }
                            }
                        ]
                    }
                }
            ],
            dataZoom: [
                {
                    type: 'inside',
                    start: 70,
                    end: 100
                }
            ]
        };

        chartInstance.setOption(option);
    };

    // 更新图表数据
    const updateChart = () => {
        if (!chartInstance) return;

        chartInstance.setOption({
            xAxis: {
                data: chartData.value.map(item => item.name)
            },
            series: [
                {
                    data: chartData.value.map(item => item.value)
                }
            ]
        });
    };

    // 切换设备
    const changeDevice = () => {
        // 清空图表数据
        chartData.value = [];

        // 重置图表
        if (chartInstance) {
            initChart();
        }

        // 重新连接WebSocket
        if (webSocket) {
            webSocket.close();
        }
        initWebSocket();

        // 模拟设备切换时数据变化
        deviceRuntime.value = Math.floor(Math.random() * 200 + 100);
        currentMetrics.value = {
            temperature: parseFloat((70 + Math.random() * 20).toFixed(1)),
            vibration: parseFloat((2.5 + Math.random() * 3.5).toFixed(1)),
            pressure: Math.floor(100 + Math.random() * 50),
            oilLevel: Math.floor(70 + Math.random() * 30)
        };

        if (currentMetrics.value.temperature > 85) {
            deviceStatus.value = '高温预警';
        } else if (currentMetrics.value.vibration > 5.0) {
            deviceStatus.value = '振动异常';
        } else {
            deviceStatus.value = '正常运行';
        }
    };

    // 显示消息弹窗
    const showMessages = () => {
        messageDialogVisible.value = true;
    };

    // 阅读消息
    const readMessage = (message) => {
        if (!message.read) {
            message.read = true;
            unreadCount.value--;
        }

        // 如果该消息有故障信息但还未查询API，则发起查询
        if (message.faultInfo && !message.apiData && !message.apiStatus) {
            fetchFaultDetailsForMessage(message);
        }
    };

    // 刷新设备信息
    const refreshDeviceInfo = () => {
        // 模拟刷新操作
        deviceInfo.value.forEach(item => {
            item.updateTime = new Date().toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            });
        });
    };

    // 刷新故障信息
    const refreshFaultInfo = () => {
        // 模拟刷新操作
        faultInfo.value.forEach(item => {
            if (item.status === '待处理' && Math.random() > 0.7) {
                item.status = '处理中';
            } else if (item.status === '处理中' && Math.random() > 0.7) {
                item.status = '已处理';
            }
        });
    };

    // 调用API查询故障详情
    const fetchFaultDetails = async (faultCode) => {
        try {
            // 构造请求体 - 使用新的故障码格式
            const requestBody = {
                mode: "global",
                response_type: "Multiple Paragraphs",
                top_k: 10,
                max_token_for_text_unit: 4000,
                max_token_for_global_context: 4000,
                max_token_for_local_context: 4000,
                only_need_context: false,
                only_need_prompt: false,
                stream: true,
                history_turns: 3,
                hl_keywords: [],
                ll_keywords: [],
                user_prompt: "",
                query: `故障码：${faultCode}，根据故障码分析故障原因以及给出维修建议，需要简短。
                    严格按以下格式返回：  【故障码】:  【故障原因】:1. 原因1 - 简要说明 2. 原因2 - 简要说明 【维修建议】:  1. 方案1 - 对应原因1的维修建议 2. 方案2 - 对应原因2的维修建议
                    【注意事项】:  - 提示1 - 提示2
                    要求： 1. 原因/方案用有序列表 2. 每个解决方案必须对应前序原因 4. 不使用Markdown表格 5. 自然语言描述故障影响 \no_thinging`
            };

            // 添加AJAX请求超时处理
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时

            const response = await fetch('http://localhost:9621/query', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestBody),
                signal: controller.signal
            });

            clearTimeout(timeoutId); // 清除超时计时器

            if (!response.ok) {
                // 尝试解析错误信息
                let errorMsg = `API请求失败: ${response.status}`;
                try {
                    const errorData = await response.json();
                    if (errorData.error) {
                        errorMsg += ` - ${errorData.error}`;
                    }
                } catch (e) {
                    console.log('解析错误响应失败:', e);
                }
                throw new Error(errorMsg);
            }

            const data = await response.json();
            return data;
        } catch (error) {
            // 更详细的错误处理
            let errorMessage = '查询故障详情失败: ';
            if (error.name === 'AbortError') {
                errorMessage += '请求超时（10秒）';
            } else if (error.message.includes('Failed to fetch')) {
                errorMessage += '网络连接错误';
            } else {
                errorMessage += error.message;
            }
            console.error(errorMessage);
            return {error: errorMessage};
        }
    };


    // 为消息获取故障详情
    const fetchFaultDetailsForMessage = async (message) => {
        // 设置加载状态
        message.apiStatus = 'loading';
        message.errorMsg = '';

        try {
            // 直接使用消息中的故障码
            const apiResult = await fetchFaultDetails(message.faultInfo);

            if (apiResult.error) {
                message.apiStatus = 'error';
                message.errorMsg = apiResult.error;
                message.apiData = null;
            } else {
                // 根据实际返回数据结构进行解析
                message.apiStatus = 'success';

                // 直接使用API返回的response字段
                if (apiResult.response) {
                    // 清洗API返回数据
                    const cleanedResponse = cleanApiResponse(apiResult.response);
                    message.apiData = `<div style="white-space: pre-wrap;">${cleanedResponse}</div>`;
                } else {
                    // 如果返回结构不同，显示原始数据（调试用）
                    message.apiData = `<pre>${JSON.stringify(apiResult, null, 2)}</pre>`;
                }
            }
        } catch (error) {
            console.error('处理API响应时出错:', error);
            message.apiStatus = 'error';
            message.errorMsg = error.message || '未知错误';
            message.apiData = null;
        }
    };

    // 测试API故障查询
    const testApiForFaultCode = async (faultCode) => {
        selectedApiFaultCode.value = faultCode;
        apiTestResult.value = {
            status: 'loading',
            text: '正在查询故障码信息...'
        };

        try {
            const apiResult = await fetchFaultDetails(faultCode);

            if (apiResult.error) {
                apiTestResult.value = {
                    status: 'error',
                    text: `API查询失败: ${apiResult.error}`,
                    statusClass: 'api-failure'
                };
            } else {
                apiTestResult.value = {
                    status: 'success',
                    text: `已成功查询故障码: ${faultCode}`,
                    // 清洗API响应
                    details: apiResult.response ? cleanApiResponse(apiResult.response) : JSON.stringify(apiResult, null, 2),
                    statusClass: 'api-success'
                };
            }
        } catch (error) {
            apiTestResult.value = {
                status: 'error',
                text: `API请求失败: ${error.message}`,
                statusClass: 'api-failure'
            };
        }
    };

    // 发送高温预警消息
    const sendHighTemperatureAlert = (temperature) => {
        const now = Date.now();
        // 避免短时间重复发送
        if (now - lastHighTempAlertTime.value < 30000) {
            return;
        }

        lastHighTempAlertTime.value = now;

        // 随机选择一个故障码
        const randomFaultCode = apiFaultCodes.value[
            Math.floor(Math.random() * apiFaultCodes.value.length)
            ];

        const newMessage = {
            id: Date.now(),
            title: '高温预警',
            content: `设备 ${selectedDevice.value} 温度超过85℃安全阈值，当前温度 ${temperature}℃。关联故障码: ${randomFaultCode}`,
            time: new Date().toLocaleTimeString('zh-CN', {hour12: false}),
            read: false,
            type: 'critical',
            faultInfo: randomFaultCode
        };

        messages.value.unshift(newMessage);
        unreadCount.value++;

        // 更新故障统计
        faultStats.value.today++;
        faultStats.value.week++;
        faultStats.value.pending++;
    };

    // 新增数据清洗函数
    const cleanApiResponse = (text) => {
        const pattern = /<think>[\s\S]*?<\/think>/g;
        return text.replace(pattern, '');
    };

    // WebSocket实例 - 用于设备数据
    let webSocket = null;
    // WebSocket实例 - 专门用于报警信息
    let warningWebSocket = null;
    const RECONNECT_DELAY = 5000; // 重连延迟5秒

    // 初始化设备数据WebSocket连接
    const initWebSocket = () => {
        connectionStatus.value = 'connecting';
        webSocket = new WebSocket('ws://localhost:1880/ws/special-vehicles');

        webSocket.addEventListener('open', () => {
            console.log('设备数据WebSocket连接已建立');
            connectionStatus.value = 'connected';
        });

        webSocket.addEventListener('message', (event) => {
            try {
                const data = JSON.parse(event.data);
                if (data.device === selectedDevice.value) {
                    // 更新设备状态
                    currentMetrics.value.temperature = data.temperature;
                    currentMetrics.value.vibration = data.vibration;

                    // 更新设备状态文本
                    if (data.temperature > 85) {
                        deviceStatus.value = '高温预警';
                    } else if (data.vibration > 5.0) {
                        deviceStatus.value = '振动异常';
                    } else {
                        deviceStatus.value = '正常运行';
                    }

                    // 创建新的数据点
                    const now = new Date();
                    const timeStr = now.toLocaleTimeString('zh-CN', {hour12: false});

                    const newDataPoint = {
                        name: timeStr,
                        value: [
                            timeStr,
                            chartType.value === 'temperature'
                                ? data.temperature
                                : data.vibration
                        ]
                    };

                    // 添加到数据数组
                    chartData.value.push(newDataPoint);
                    if (chartData.value.length > 100) {
                        chartData.value.shift();
                    }

                    // 更新图表
                    updateChart();
                }
            } catch (error) {
                console.error('解析设备数据失败:', error);
            }
        });

        webSocket.addEventListener('error', (error) => {
            console.error('设备数据WebSocket错误:', error);
            connectionStatus.value = 'disconnected';
        });

        webSocket.addEventListener('close', () => {
            console.log('设备数据连接断开，5秒后重连...');
            connectionStatus.value = 'disconnected';
            setTimeout(initWebSocket, RECONNECT_DELAY);
        });
    };

    // 初始化报警信息WebSocket连接
    const initWarningWebSocket = () => {
        warningWebSocket = new WebSocket('ws://localhost:1880/ws/warning');

        warningWebSocket.addEventListener('open', () => {
            console.log('报警信息WebSocket连接已建立');
        });

        warningWebSocket.addEventListener('message', (event) => {
            try {
                // 修改点：正确解析 msg.payload 结构
                const msg = JSON.parse(event.data);
                // 确保获取 payload 对象
                const payload = msg.payload || msg;

                console.log('收到报警信息:', payload);

                // 随机选择一个状态码
                const faultCodes = [
                    'MSV-P001', 'MSV-P010', 'MSV-C101',
                    'MSV-A201', 'MSV-F301', 'MSV-D401'
                ];
                const randomFaultCode = faultCodes[Math.floor(Math.random() * faultCodes.length)];

                // 确定报警类型和内容
                let alertType, alertTitle, alertContent;

                if (payload.temperature > 85) {
                    alertType = 'critical';
                    alertTitle = '高温报警';
                    alertContent = `设备 ${payload.device} 温度过高 (${payload.temperature}℃)`;
                } else if (payload.vibration > 5.0) {
                    alertType = 'warning';
                    alertTitle = '振动报警';
                    alertContent = `设备 ${payload.device} 振动异常 (${payload.vibration}g)`;
                } else {
                    // 如果既不是高温也不是振动报警，则创建一般性报警
                    alertType = 'warning';
                    alertTitle = '设备异常';
                    alertContent = `设备 ${payload.device} 出现异常状态`;
                }

                // 创建新的报警消息
                const newMessage = {
                    id: Date.now(),
                    title: alertTitle,
                    content: alertContent,
                    time: new Date().toLocaleTimeString('zh-CN', {hour12: false}),
                    read: false,
                    type: alertType,
                    faultInfo: randomFaultCode  // 使用随机选择的状态码
                };

                // 添加到消息列表顶部
                messages.value.unshift(newMessage);
                unreadCount.value++;

                // 更新故障统计
                faultStats.value.today++;
                faultStats.value.week++;
                faultStats.value.pending++;

                // 弹出通知
               /* ElNotification({
                    title: newMessage.title,
                    message: newMessage.content,
                    type: 'warning',
                    duration: 6000
                });*/

            } catch (error) {
                console.error('解析报警信息失败:', error);
            }
        });

        warningWebSocket.addEventListener('error', (error) => {
            console.error('报警信息WebSocket错误:', error);
        });

        warningWebSocket.addEventListener('close', () => {
            console.log('报警信息连接断开，5秒后重连...');
            setTimeout(initWarningWebSocket, 5000);
        });
    };


    onMounted(() => {
        updateTime();
        setInterval(updateTime, 1000);
        initChart();
        initWebSocket();
        initWarningWebSocket();  // 初始化报警信息WebSocket

        // 窗口大小变化时重绘图表
        window.addEventListener('resize', () => {
            if (chartInstance) {
                chartInstance.resize();
            }
        });
    });

    onBeforeUnmount(() => {
        // 清理资源
        if (webSocket) {
            webSocket.close();
        }
        if (warningWebSocket) {
            warningWebSocket.close();
        }
        if (chartInstance) {
            chartInstance.dispose();
        }
        window.removeEventListener('resize', () => {
        });
    });
    return {
        deviceOptions,
        selectedDevice,
        currentTime,
        chart,
        deviceStatus,
        deviceRuntime,
        currentMetrics,
        faultStats,
        deviceInfo,
        faultInfo,
        unreadCount,
        messageDialogVisible,
        messages,
        deviceStatusClass,
        connectionStatusClass,
        connectionStatusText,
        changeDevice,
        toggleChartData,
        resetZoom,
        showMessages,
        readMessage,
        refreshDeviceInfo,
        refreshFaultInfo,
        apiFaultCodes,
        selectedApiFaultCode,
        apiTestResult,
        testApiForFaultCode
    }
}
